package com.sdkj.fixed.asset.assets.controller;

import com.alibaba.fastjson.JSONObject;
import com.sdkj.fixed.asset.api.assets.MaintainRegisterApi;
import com.sdkj.fixed.asset.api.assets.in_vo.AppApplyMaintain;
import com.sdkj.fixed.asset.api.assets.in_vo.MaintainRegisterExtend;
import com.sdkj.fixed.asset.api.assets.in_vo.Params;
import com.sdkj.fixed.asset.api.assets.in_vo.SelPrams;
import com.sdkj.fixed.asset.api.assets.out_vo.WarehouseBase;
import com.sdkj.fixed.asset.assets.service.MaintainRegisterService;
import com.sdkj.fixed.asset.assets.util.DateTools;
import com.sdkj.fixed.asset.assets.util.ExcelStyle;
import com.sdkj.fixed.asset.assets.util.ExcelUtils;
import com.sdkj.fixed.asset.common.base.BaseResultVo;
import com.sdkj.fixed.asset.common.base.PageBean;
import com.sdkj.fixed.asset.common.base.PageParams;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author niuliwei
 * @description 维修信息登记
 * @date 2020/7/27 11:21
 */
@Controller
public class MaintainRegisterController implements MaintainRegisterApi {
    private final Logger log = LoggerFactory.getLogger(MaintainRegisterController.class);
    @Autowired
    private MaintainRegisterService service;
    @Autowired
    private HttpServletResponse response;

    @Override
    public BaseResultVo appApply(AppApplyMaintain params) throws Exception {
        log.info("APP报修参数："+JSONObject.toJSONString(params));
        service.appApply(params);
        return BaseResultVo.success();
    }

    @Override
    public BaseResultVo add(MaintainRegisterExtend register) {
        service.add(register,"PC");
        return BaseResultVo.success(register.getId());
    }

    @Override
    public BaseResultVo getAllPage(PageParams<SelPrams> param) {
        List<MaintainRegisterExtend> list = service.getAllPage(param);
        PageBean pageBean = new PageBean(list);
        return BaseResultVo.success(pageBean);
    }

    @Override
    public BaseResultVo selById(Params params) {
        MaintainRegisterExtend extend = service.selById(params.getId());
        return BaseResultVo.success(extend);
    }

    @Override
    public void exportExcel(String startDate, String endDate, String orgId, String token) throws IOException {
        List<MaintainRegisterExtend> list = service.exportExcel(startDate, endDate, orgId, token);
        if(list == null || list.size()<=0){
            list = new ArrayList<>();
        }
        String title = "维修信息登记单";
        String sheetName = "维修信息登记单";
        String fileName = "维修信息登记单" + DateTools.dateToString(new Date(), "yyyyMMddHHmmss");
        ExcelUtils.exportExcel(list, title, sheetName, MaintainRegisterExtend.class, fileName, response);
    }

    @Override
    public BaseResultVo updateInfo(MaintainRegisterExtend register) {
        service.updateInfo(register);
        return BaseResultVo.success();
    }

    @Override
    public BaseResultVo maintainStart(Params params) {
        service.maintainStart(params.getId());
        return BaseResultVo.success();
    }

    @Override
    public BaseResultVo maintainEnd(Params params) {
        service.maintainEnd(params.getId());
        return BaseResultVo.success();
    }

    @Override
    public void print(String id) throws IOException {
        MaintainRegisterExtend extend = service.selById(id);
        String title = "资产维修单";
        String sheetName = "资产维修";
        String fileName = "资产维修单";

//        创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFRow row = null;
        HSSFCell cell = null;
        int rownum = 0;
        // 建立新的sheet对象（excel的表单） 并设置sheet名字
        HSSFSheet sheet = wb.createSheet(sheetName);
        ExcelStyle.printSetup(sheet);
        sheet.setDefaultColumnWidth(18);
        sheet.setColumnWidth(0, 256 * 6);
        sheet.setDefaultRowHeight((short) 512);

        // 在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
        row = sheet.createRow(rownum++);
        row.setHeight((short) 1000 );
        // 创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
        cell = row.createCell(1);
        // 合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 8));
        cell.setCellValue(title);
        cell.setCellStyle(ExcelStyle.styleTitle(wb));

        String[] row1 = {"维修单号：", extend.getNumber(), "", "","业务日期：", extend.getDate(), "", ""};
        String[] row2 = {"处理人：", extend.getOperator(), "", "", "维修花费：", extend.getCost(), "", ""};
        String[] row3 = {"维修内容：", extend.getRepairsContent(), "", "", "", "", "", ""};
        String[] row4 = {"备注：", extend.getNote(), "", "", "", "", "", ""};
        String[] row5 = {"维修资产明细："};
        String[] row6 = {"序号","资产编码","资产名称","所属公司","使用公司","使用部门","使用人","存放地址"};

        List<String[]> rowList = new ArrayList<>();
        rowList.add(row1);
        rowList.add(row2);
        rowList.add(row3);
        rowList.add(row4);
        rowList.add(row5);
        rowList.add(row6);

        for (String[] rows : rowList) {
            row = sheet.createRow(rownum++);
            for (int i = 0; i < rows.length; i++) {
                cell = row.createCell(i + 1);
                cell.setCellValue(rows[i]);
                if(rownum == 6){
                    cell.setCellStyle(ExcelStyle.styleNotBorder(wb, 3));
                    row.setHeight((short)700);
                } else if (rownum == 7){
                    cell.setCellStyle(ExcelStyle.styleCellName(wb));
                } else {
                    cell.setCellStyle(ExcelStyle.styleNotBorder(wb, 2));
                }

            }
        }

        //遍历数据
        int j = 1;
        for (WarehouseBase result : extend.getResults()) {
            row = sheet.createRow(rownum++);
            String[] cells = {"", result.getAssetCode(), result.getAssetName(), result.getCompanyName(), result.getUseCompanyName(), result.getUseDeptName(), result.getHandlerUser(), result.getStorageLocation()};
            for (int i = 0; i < cells.length; i++) {
                cell = row.createCell(i + 1);
                if(i==0){
                    cell.setCellValue(j++);
                } else {
                    cell.setCellValue(cells[i]);
                }
                cell.setCellStyle(ExcelStyle.styleCellValue(wb));
            }
        }

        // 输出Excel文件
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition","attachment; filename="+ URLEncoder.encode(fileName + ".xlsx", "UTF-8"));    //filename =  文件名
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
    }

    @Override
    public BaseResultVo delById(Params params) {
        service.delById(params.getId());
        return BaseResultVo.success();
    }
}
